package com.certificationManager.server.domain.dao.jdo;

import java.util.Date;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import org.apache.log4j.Logger;

import com.certificationManager.client.bean.UserBean;
import com.certificationManager.server.domain.dao.UserDAO;
import com.certificationManager.server.domain.manager.jdo.PMF;
import com.certificationManager.server.domain.model.User;
import com.certificationManager.server.service.jbcrypt.BCrypt;
import com.google.appengine.repackaged.com.google.common.base.StringUtil;

/**
 * @author Benjamin Barbier
 *
 */
public class UserDAOJdo implements UserDAO {

	/** A Bo should never be instantiated */
	private UserDAOJdo() {}
	
	private static final UserDAOJdo singleton = new UserDAOJdo();
	
	public static UserDAOJdo getInstance() {return singleton;}
	
	/** Logger */
	private static final Logger logger = Logger.getLogger(UserDAOJdo.class); 
	
	public void inscription(UserBean newUserBean) {

		User newUser = null;
		
		// Entity Manager Factory
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try {
			//TODO: mettre la bonne langue
//			Language language = pm.getObjectById(Language.class, "FR"/*newUserBean.getLanguage()*/);

//			if (language == null) {throw new Exception();}
			
			newUser = new User(
				newUserBean.getLastName(), 
				newUserBean.getFirstName(), 
				newUserBean.getEmail(), 
				BCrypt.hashpw(newUserBean.getPassword(), BCrypt.gensalt()), 
				new Date()
//				, language
				);
			pm.makePersistent(newUser);
		} catch (Exception e) {
			logger.error("L'inscription a echouee.", e);
		} finally {
			pm.close();
		}
		
	}
	
	/**
	 * @param email
	 * @return
	 */
	public boolean existUtilisateur(String email) {
		
		if (StringUtil.isEmptyOrWhitespace(email)) return false;
		
		// Entity Manager Factory
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try {
			// If User not found, throw new JDOObjectNotFoundException and return false;
			pm.getObjectById(User.class, email);
			return true;
		} catch (JDOObjectNotFoundException e) {
			return false;	
		} finally {
			// Fermeture du EMF
	        pm.close();
	    }
		
	}
	
	/**
	 * @param email
	 * @param password
	 * @return
	 */
	public boolean isRegistered(String email, String password) {

		// Entity Manager Factory
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		
		if (StringUtil.isEmptyOrWhitespace(email)) return false;
		if (StringUtil.isEmptyOrWhitespace(password)) return false;
		
		User user = pm.getObjectById(User.class, email); 
		
		if (user != null && BCrypt.checkpw(password, user.getPassword())) { 
			return true;
		} else {
			return false;
		}
		
	}
	
}
